package leetcode.editor.cn;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;

/**
 * @author: yangwk
 * @date: 2023/2/21
 * @description:
 **/
public class P127 {
    public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
        boolean[] visited = new boolean[wordList.size()];
        Queue<String> queue = new ArrayDeque<>();
        queue.add(beginWord);
        int count = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            count++;
            while (size-- > 0) {
                String poll = queue.poll();
                if (poll.equals(endWord)) {
                    return count;
                }
                for (int i = 0; i < wordList.size(); i++) {
                    String s = wordList.get(i);
                    if (visited[i] || !diff(poll, s)) {
                        continue;
                    }
                    visited[i] = true;
                    queue.offer(wordList.get(i));
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        String beginWord = "hit";
        String endWord = "cog";
        String[] wordList = new String[]{"hot", "dot", "dog", "lot", "log", "cog"};
        System.out.println(ladderLength(beginWord, endWord, Arrays.asList(wordList)));
    }

    public static boolean diff(String str1, String str2) {
        int length = str1.length();
        int diff = 0;
        for (int i = 0; i < length; i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                diff++;
            }
        }
        return diff <= 1;
    }
}
